package com.learn.metrics.type.counter;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;
import com.learn.metrics.util.MetricUtil;
import lombok.experimental.UtilityClass;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 计数值
 * <p>支持增加、减少</p>
 * @author XuYang
 * @since 2025/2/18 21:46
 */
@UtilityClass
public class CounterExample {
    Queue<String> queue = new LinkedBlockingQueue<>();
    Counter counter;

    public void start() {
        MetricUtil.startReporter(2);
        counter = MetricUtil.REGISTRY.counter(MetricRegistry.name(Queue.class, "jobs", "size"));
        doRun();
    }


    private void doRun() {
        int num = 1;
        while (true) {
            ThreadUtil.sleep(200);
            if (RandomUtil.randomDouble() > 0.7) {
                takeJob();
            } else {
                addJob("Job-" + num);
            }
            num++;
        }
    }

    private static void addJob(String job) {
        counter.inc();
        queue.offer(job);
    }

    private static String takeJob() {
        counter.dec();
        return queue.poll();
    }
}
